#!/usr/bin/env python3
"""
PR Patch 生成器 - GUI 版本
使用 tkinter 创建简单界面
"""

import xml.etree.ElementTree as ET
import tkinter as tk
from tkinter import scrolledtext, messagebox
import sys
import os
import urllib.parse

class PRPatchGenerator:
    def __init__(self):
        current_dir = os.path.dirname(os.path.abspath(__file__))
        self.ohos_xml_path = os.path.join(current_dir, "ohos.xml")
        self.project_map = {}
        self.setup_ui()
        self.load_manifest()
    
    def setup_ui(self):
        """设置用户界面"""
        self.root = tk.Tk()
        self.root.title("PR Patch 生成器 v1.0")
        self.root.geometry("800x600")
        
        # 标题
        title_label = tk.Label(self.root, text="PR Patch 生成器", 
                              font=("Arial", 16, "bold"))
        title_label.pack(pady=10)
        
        # 输入区域框架
        input_frame = tk.LabelFrame(self.root, text="输入 PR URL (每行一个)", padx=10, pady=10)
        input_frame.pack(fill="both", expand=True, padx=20, pady=5)
        
        # 输入文本框
        self.input_text = scrolledtext.ScrolledText(input_frame, height=8)
        self.input_text.pack(fill="both", expand=True)
        
        # 示例文本
        example_label = tk.Label(input_frame, text="示例: https://gitcode.com/openharmony/arkui_ace_engine/pull/77005",
                                font=("Arial", 9), fg="gray")
        example_label.pack(pady=5)
        
        # 按钮框架
        button_frame = tk.Frame(self.root)
        button_frame.pack(pady=10)
        
        # 生成按钮
        self.generate_btn = tk.Button(button_frame, text="生成命令", 
                                     command=self.generate_commands,
                                     bg="#4CAF50", fg="white",
                                     font=("Arial", 10, "bold"),
                                     padx=20, pady=5)
        self.generate_btn.pack(side="left", padx=10)
        
        # 清空按钮
        clear_btn = tk.Button(button_frame, text="清空", 
                             command=self.clear_all,
                             bg="#f44336", fg="white",
                             font=("Arial", 10),
                             padx=20, pady=5)
        clear_btn.pack(side="left", padx=10)
        
        # 输出区域框架
        output_frame = tk.LabelFrame(self.root, text="生成的命令 (可复制)", padx=10, pady=10)
        output_frame.pack(fill="both", expand=True, padx=20, pady=5)
        
        # 输出文本框
        self.output_text = scrolledtext.ScrolledText(output_frame, height=12)
        self.output_text.pack(fill="both", expand=True)
        
        # 复制按钮
        copy_btn = tk.Button(output_frame, text="复制全部命令", 
                           command=self.copy_to_clipboard,
                           bg="#2196F3", fg="white",
                           font=("Arial", 10),
                           padx=10, pady=2)
        copy_btn.pack(pady=5)
        
        # 状态栏
        self.status_bar = tk.Label(self.root, text="就绪", bd=1, relief=tk.SUNKEN, anchor=tk.W)
        self.status_bar.pack(side=tk.BOTTOM, fill=tk.X)
    
    def load_manifest(self):
        """加载 ohos.xml 文件"""
        try:
            if not os.path.exists(self.ohos_xml_path):
                messagebox.showerror("错误", f"找不到 ohos.xml 文件:\n{self.ohos_xml_path}")
                self.root.quit()
                return
            
            tree = ET.parse(self.ohos_xml_path)
            root = tree.getroot()
            
            self.project_map = {}
            for project in root.findall('project'):
                name = project.get('name')
                path = project.get('path')
                
                if name and path:
                    self.project_map[name] = {
                        'path': path,
                        'name': name
                    }
            
            self.update_status(f"已加载 {len(self.project_map)} 个项目")
            
        except Exception as e:
            messagebox.showerror("错误", f"解析 XML 失败:\n{str(e)}")
            self.root.quit()
    
    def update_status(self, message):
        """更新状态栏"""
        self.status_bar.config(text=message)
        self.root.update_idletasks()
    
    def find_project_by_name(self, project_name):
        """根据项目名称查找项目信息"""
        if project_name in self.project_map:
            return self.project_map[project_name]
        
        for name, info in self.project_map.items():
            if name.endswith('/' + project_name) or name == project_name:
                return info
        
        for name, info in self.project_map.items():
            if project_name.lower() in name.lower():
                return info
        
        return None
    
    def parse_pr_url(self, pr_url):
        """解析 PR URL"""
        try:
            parsed = urllib.parse.urlparse(pr_url)
            path_parts = parsed.path.strip('/').split('/')
            
            if len(path_parts) >= 4 and path_parts[2] in ['pull', 'merge_requests']:
                project_name = '/'.join(path_parts[0:2])
                pr_number = path_parts[3]
                return project_name, pr_number
            
            return None, None
        except:
            return None, None
    
    def generate_commands(self):
        """生成命令"""
        # 清空输出
        self.output_text.delete(1.0, tk.END)
        
        # 获取输入
        input_content = self.input_text.get(1.0, tk.END).strip()
        if not input_content:
            messagebox.showwarning("提示", "请输入 PR URL")
            return
        
        pr_urls = [url.strip() for url in input_content.split('\n') if url.strip()]
        
        self.update_status(f"正在处理 {len(pr_urls)} 个 PR URL...")
        
        commands = []
        success_count = 0
        fail_count = 0
        
        for i, pr_url in enumerate(pr_urls, 1):
            self.update_status(f"处理第 {i}/{len(pr_urls)} 个: {pr_url[:40]}...")
            
            project_name, pr_number = self.parse_pr_url(pr_url)
            
            if not project_name or not pr_number:
                self.output_text.insert(tk.END, f"# 错误: {pr_url[:50]}... - URL格式错误\n\n")
                fail_count += 1
                continue
            
            # 提取项目名最后部分
            project_name_parts = project_name.split('/')
            short_project_name = project_name_parts[-1] if len(project_name_parts) > 1 else project_name
            
            # 查找项目
            project_info = self.find_project_by_name(short_project_name)
            if not project_info:
                self.output_text.insert(tk.END, f"# 错误: 未找到项目 {short_project_name}\n\n")
                fail_count += 1
                continue
            
            # 生成命令
            project_path = project_info['path']
            project_name = project_info['name']
            refspec = f"+refs/merge-requests/{pr_number}/head"
            branch_name = f"pr_{pr_number}"
            
            fetch_cmd = f"cd {project_path} && git fetch https://gitcode.com/openharmony/{project_name}.git {refspec}:{branch_name} && git merge {branch_name} --no-edit && cd -;"
            commands.append(fetch_cmd)
            
            self.output_text.insert(tk.END, fetch_cmd + "\n")
            success_count += 1
        
        # 显示统计信息
        # self.output_text.insert(tk.END, f"\n{'='*60}\n")
        # self.output_text.insert(tk.END, f"统计: 成功 {success_count} 个, 失败 {fail_count} 个\n")
        
        self.update_status(f"完成: 成功 {success_count} 个, 失败 {fail_count} 个")
        
        if success_count > 0:
            messagebox.showinfo("完成", f"成功生成 {success_count} 个命令")
    
    def copy_to_clipboard(self):
        """复制所有命令到剪贴板"""
        content = self.output_text.get(1.0, tk.END).strip()
        if content:
            self.root.clipboard_clear()
            self.root.clipboard_append(content)
            messagebox.showinfo("成功", "命令已复制到剪贴板")
        else:
            messagebox.showwarning("提示", "没有可复制的内容")
    
    def clear_all(self):
        """清空所有内容"""
        self.input_text.delete(1.0, tk.END)
        self.output_text.delete(1.0, tk.END)
        self.update_status("已清空")
    
    def run(self):
        """运行程序"""
        self.root.mainloop()

if __name__ == "__main__":
    app = PRPatchGenerator()
    app.run()